<template>
    <Dialog ref="dialogRef" :app-dialog="appDialog" @close="close">
        <el-scrollbar min-height="100px" max-height="560px">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="110px">
                <!-- 分组 -->
                <el-form-item label="分组" style="padding-top: 14px">
                    <el-cascader
                        ref="cascaderRef"
                        v-model="form.group"
                        style="width: 100%"
                        :options="groupData"
                        :props="defaultProps"
                        placeholder="请选择分组"
                        @change="orgChange" />
                </el-form-item>
                <!-- 类型 -->
                <el-form-item label="类型">
                    <el-radio-group v-model="form.type" class="radio_list" @change="changeType">
                        <el-radio
                            v-for="item in typeDiff"
                            :key="item.value"
                            :label="item.value"
                            class="radio_list_item">
                            <span class="radio_list_item_text">{{ item.name }}</span>
                            <el-tooltip v-if="item.value === 1" :content="item.text" placement="bottom">
                                <div class="radio_list_item_icon radio_img">
                                    <img src="@/assets/image/material/question.png" alt="" />
                                </div>
                            </el-tooltip>
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <!-- 上传文件 -->
                <!-- 上传文件 -->
                <el-form-item label="图片" prop="images">
                    <ZWUpload
                        v-if="appDialog.visible"
                        ref="emptyData"
                        :up-info="picInfo"
                        @submit="getFileList"></ZWUpload>
                </el-form-item>
                <el-form-item>
                    <template #label>
                        <div class="label_text">
                            <span>素材标签</span>
                            <el-tooltip :content="tagTips.materialTagTips" placement="top">
                                <img src="@/assets/image/material/question.png" alt="" />
                            </el-tooltip>
                        </div>
                    </template>
                    <selectTags ref="tagIdsRef" v-model="form.tag_ids" />
                </el-form-item>
                <el-form-item v-show="form.type == 1" label="是否强制授权">
                    <el-radio-group v-model="form.is_force_grant" @change="changeAuth">
                        <el-radio :label="1">否</el-radio>
                        <el-radio :label="2">是</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item v-show="form.is_force_grant == 2 && form.type == 1" label="授权内容">
                    <el-checkbox-group v-model="form.grant_params">
                        <el-checkbox label="offical_headimg_nickname">头像昵称（公众号）</el-checkbox>
                        <el-checkbox label="phone">手机号（小程序）</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item v-if="form.type == 1">
                    <template #label>
                        <div class="label_text">
                            <span>浏览打标</span>
                            <el-tooltip :content="tagTips.browseCustTips" placement="top">
                                <img src="@/assets/image/material/question.png" alt="" />
                            </el-tooltip>
                        </div>
                    </template>
                    <selectTags ref="viewtagIdsRef" v-model="form.view_tag_ids" :type="2" />
                </el-form-item>
                <el-form-item v-if="form.type == 1">
                    <template #label>
                        <div class="label_text">
                            <span>分享打标</span>
                            <el-tooltip :content="tagTips.shareCustTips" placement="top">
                                <img src="@/assets/image/material/question.png" alt="" />
                            </el-tooltip>
                        </div>
                    </template>
                    <selectTags ref="shareTagIdsRef" v-model="form.share_tag_ids" :type="2" />
                </el-form-item>
                <el-form-item label="">
                    <div class="agree_ment">
                        <!-- 暂时隐藏掉,协议要先不上需要法务确认 -->

                        <!-- <el-checkbox v-model="form.check" @change="confirmSure"></el-checkbox>
            <span class="ml2">勾选代表同意</span>
            <el-link class="form-link" type="primary" :underline="false">《***用户协议》</el-link> -->
                    </div>
                </el-form-item>
            </el-form>
        </el-scrollbar>
    </Dialog>
</template>
<script setup lang="ts">
import { ref, reactive, computed, watch, onUnmounted } from 'vue';
import Dialog from '@/components/Dialog.vue';
import ZWUpload from './ZWUpload.vue';
import selectTags from '../../../components/selectTags.vue';
import { modifyImage, imagesInfo, uploadImage, getGroupList } from '@/api/concreation';
import { ElForm, ElMessage } from 'element-plus';
import { getSetionId, IsNotEmpty } from '@/utils/utils';
import bus from '@/utils/bus';
const formRef = ref<InstanceType<typeof ElForm>>();
const emit = defineEmits(['submit']);
const props = defineProps(['groupId', 'type']);
import { useStore } from '@/store';
const store = useStore();
const cascaderRef: any = ref(null); // 选择分组ref
const dialogRef = ref(null);
const uploadTitle = ref('上传文件');
const uploadVisib = ref(false);
const isEdit = ref(false);
const emptyData = ref(); // 清空回显数据
const tagIdsRef = ref(null);
const viewtagIdsRef = ref(null);
const shareTagIdsRef = ref(null);
const tagTips = {
    materialTagTips: '该素材会被打上此素材标签，在列表上会展示',
    browseCustTips: '浏览该素材的客户将被打上此客户标签',
    shareCustTips: '点击该素材的分享按钮并生成分享链接的客户将被打上此客户标签'
};
const changeType = (val: any) => {
    if (val == 0) {
        form.is_force_grant = '';
    } else if (val == 1) {
        form.is_force_grant = 1;
    }
};
//上传弹框
const uploadInfo = computed(() => {
    return store.getters['content/upload'];
});
// 分组列表
const groupData = ref([]);

/**
 * @description: 获取分组数据
 * @return {*}
 */
const getGroupListFunc = async () => {
    const res = await getGroupList({ type: props.type });
    groupData.value = res.data;
};

//标签
const tags = computed(() => {
    return store.getters['content/tagsInfo'].tags;
});
const defaultProps = {
    checkStrictly: true,
    emitPath: false,
    label: 'name',
    value: 'id'
};
const form = reactive({
    tag_ids: [],
    view_tag_ids: [],
    is_force_grant: 1,
    group: 0, //分组
    type: 0, //图片类型
    images: [], // 图片
    tags: [], //标签
    share_tag_ids: [],
    grant_params: ['offical_headimg_nickname', 'phone'],
    check: true, //用户协议
    // title: '', //标题
    id: '' //内容id
});

const rules = reactive({
    title: [
        {
            required: true,
            message: '标题不能为空',
            trigger: 'blur'
        }
    ],
    images: [
        {
            required: true,
            message: '图片不能为空',
            trigger: 'click'
        }
    ]
});
// 图片上传
const picInfo = reactive({
    type: 1,
    label: '图片',
    prop: 'images',
    files: form.images,
    multiple: true,
    limitSize: 10,
    limitNum: 9,
    // acceptFile: '.jpg,.jpeg,.png,.gif,.bmp,.webp'
    acceptFile: '.jpg,.JPG,.jpeg,.JPEG,.png,.PNG'
});
const typeDiff = reactive([
    { value: 0, name: `普通图片` },
    {
        value: 1,
        name: `雷达图片`,
        text: `雷达图片可以追踪客户端浏览次数、时间等数据`
    }
]);
const confirmSure = (val: boolean) => {
    appDialog.isDisable = !val;
};
const changeAuth = () => {
    if (form.is_force_grant == 1) {
        form.grant_params = [];
    } else {
        form.grant_params = ['offical_headimg_nickname', 'phone'];
    }
};
// 获取上传成功的文件
const getFileList = (data: any) => {
    data = data.filter((item: any) => IsNotEmpty(item));
    if (data.length > 0) {
        form.images = getSetionId('code', data);
    } else {
        form.images = [];
    }
};
// 取消
const cancelHandel = () => {
    appDialog.visible = false;
    isEdit.value = false;
    delUpform();
    close();
    formRef.value.resetFields();
};
//确定
const submitHandel = () => {
    formRef.value.validate(async (valid: any) => {
        if (valid) {
            const grant = {
                offical_headimg_nickname: form.grant_params.includes('offical_headimg_nickname') ? 2 : 1,
                phone: form.grant_params.includes('phone') ? 2 : 1
            };
            const params = {
                title: form.title,
                group_id: form.group,
                file_type: form.type,
                code: Array.isArray(form.images) ? form.images : [form.images],
                tag_ids: getSetionId('id', form.tag_ids),
                view_tag_ids: getSetionId('id', form.view_tag_ids),
                is_force_grant: form.is_force_grant,
                grant_params: grant,
                share_tag_ids: getSetionId('id', form.share_tag_ids)
            };
            if (form.type === 0) {
                delete params.view_tag_ids;
                delete params.share_tag_ids;
            }
            // 修改
            if (isEdit.value) {
                // 图片编辑
                params.media_content_id = form.id;
                modifyImage(params).then((data: any) => {
                    isEdit.value = false;
                    ElMessage.success('修改成功');
                    emit('submit', { id: form.group });
                    cancelHandel();
                });
            } else {
                emptyData.value.upPic();
                uploadImage(params).then((res: any) => {
                    emit('submit', { id: form.group });
                    delUpform();
                    ElMessage.success('图片创建成功');
                    cancelHandel();
                });
            }
        }
    });
};
const appDialog = reactive({
    visible: uploadVisib,
    title: '上传图片',
    width: '670px',
    cancel: cancelHandel,
    submit: submitHandel,
    isDisable: false,
    cancelText: '取消',
    submitText: '保存'
});
const close = () => {
    form.group = props.groupId;
};
//获取编辑内容
const editItem = (item: any) => {
    appDialog.title = '编辑图片';
    isEdit.value = true;
    imagesInfo({
        media_content_id: item.id
    }).then((data: any) => {
        // tag_ids 素材标签
        // view_tag_ids 浏览客户标签
        // share_tag_ids 分享客户标签
        form.tag_ids = data.tag_info;
        form.view_tag_ids = data.view_tag_info;
        form.share_tag_ids = data.share_tag_info;
        form.group = data.group_id;
        form.images = data.mediaFileInfo[0]?.code;
        form.tags = data.tagInfo || [];
        form.type = data.is_radar;
        form.id = data.id;
        form.is_force_grant = data.is_force_grant;
        form.grant_params = [];
        if (data.grant_params && data.grant_params?.offical_headimg_nickname == 2) {
            form.grant_params.push('offical_headimg_nickname');
        }
        if (data.grant_params && data.grant_params?.phone == 2) {
            form.grant_params.push('phone');
        }
        item.write = false;
        emptyData.value.echo(data.mediaFileInfo);
        setTimeout(() => {
            tagIdsRef.value?.init();
            viewtagIdsRef.value?.init();
            shareTagIdsRef.value?.init();
        }, 0);
    });
};
// 清空上传表单数据
const delUpform = () => {
    Object.keys(form).map(key => {
        if (key !== 'group' && key !== 'type' && key !== 'check') {
            if (key === 'tags') {
                form[key].length = 0;
            } else {
                delete form[key];
            }
        }
    });
    emptyData.value.empty();
};
bus.on('delUpform', delUpform);
bus.on('editItem', editItem);
watch(uploadInfo, uploadInfo => {
    uploadTitle.value = uploadInfo.title;
    uploadVisib.value = uploadInfo.uploadVisib;
    if (uploadVisib.value) {
        getGroupListFunc();
    }
    form.grant_params = ['offical_headimg_nickname', 'phone'];
    form.is_force_grant = 1;
});
watch(
    () => props.groupId,
    val => {
        form.group = val;
    }
);
watch(tags, data => {
    form.tags = data;
});

// 选择完地区后立即关闭
const orgChange = () => {
    cascaderRef.value.togglePopperVisible();
};
onUnmounted(() => {
    bus.off('editItem', editItem);
});
</script>

<style lang="scss" scoped>
.radio_list {
    height: 40px;

    &_item {
        &_icon {
            width: 14px;
            height: 14px;
            margin: -3px 0 0 6px;

            img {
                margin-top: 2px;
                width: 100%;
                height: 100%;
                vertical-align: top;
            }
        }
    }

    :deep .el-radio__label {
        display: flex;
        align-items: center;
    }
}

.ml2 {
    margin-left: 2px;
}

.mr10 {
    margin-right: 10px;
}

.agree_ment {
    display: flex;
    align-items: center;
}

:deep .el-scrollbar {
    height: 50%;
}

:deep .el-dialog__body {
    padding: calc(var(--el-dialog-padding-primary) + 0px) var(--el-dialog-padding-primary);
}

:deep .app_dialog .el-dialog__body {
    padding: 0 !important;
}

:deep(.el-form-item) {
    margin-bottom: 14px;

    .label_text {
        display: flex;
        align-items: center;
        gap: 6px;

        img {
            width: 14px;
            height: 14px;
        }
    }
}
</style>
